package com.yjymm.commonsdk.common.component.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.yjymm.commonsdk.common.util.FileUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yjymm
 * @date 2021-01-21 23:46
 */
@Component
@EnableConfigurationProperties(OSSProperties.class)
public class OSSComponent {

    @Resource
    private OSSClient ossClient;

    @Resource
    private OSSProperties ossProperties;


    /**
     * 添加资源前缀
     * @param url
     * @return
     */
    public String addUrlPrefix(String url){
        if (url == null) {
            return null;
        }
        if (!url.startsWith("http")) {
            return ossProperties.getUrlPrefix() + url;
        }
        return url;
    }

    /**
     * 批量添加资源前缀
     * @param url
     * @return
     */
    public List<String> addUrlPrefixArray(String [] url){
        List<String> list = new ArrayList<>();
        for (int i = 0; i < url.length; i++) {
            if (url[i] == null) {
                continue;
            }
            if (!url[i].startsWith("http")) {
                list.add(ossProperties.getUrlPrefix() + url[i]);
            }
        }
        return list;
    }

    @Bean
    public OSS ossClient() {
        return new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
    }


    /**
     * 上传文件，返回文件名（不带前缀）
     * @param inputStream
     * @return
     */
    public String uploadFile(InputStream inputStream, String fileName) throws Exception{
        ossClient.putObject(ossProperties.getBucketName(), fileName, inputStream);
        return fileName;
    }

    public String uploadFileWithRandonFileName(InputStream inputStream, String suffix) throws Exception{
        String fileName = FileUtils.randomFileName(suffix);
        return uploadFile(inputStream, fileName);
    }

}
